<?php

class LookupService extends FServiceBase
{    
    /**
    * Get a Lookup model given its ID
    * 
    * @param int id Lookup ID
    * @return FServiceModel
    */
    public function get($params){
        $model = Lookup::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Lookup','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        /**
        * @var CModel
        */
        $model = $this->getModel($params['Lookup'],'Lookup');
        $this->result->processed('model', $model);
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Lookup', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        elseif (! $model->save())
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Admin.Lookup','Error while saving submitted data into database.'));
        
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Lookup','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = Lookup::model()->findByPk($id);
            /**
            * TODO: Check related data if this Lookup is deletable
            * This can be done in onBeforeDelete or here or in extensions
            *
            if (Related::model()->count("LookupId = {$id}") > 0)
                $this->result->fail(ERROR_VIOLATING_BUSINESS_RULES, Yii::t('Admin.Lookup',"Cannot delete Lookup ID={$id} as it has related class data."));
            else
            */
                try {
                    $model->delete();
                } catch (CDbException $ex) {
                    $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
                }
        }
        return $this->result;
    }
    
    /**
    * Used for re order the position
    * 
    * @param mixed $params
    */
    public function saveOrder($params){
        $ids=$this->getParam($params,'ids',array());
        if (count($ids)) {
            foreach ($ids as $index => $id) {
                Lookup::model()->updateByPk($id, array('position'=>$index+1));
            }
        }
        return $this->result;
    }
    /**
    *  Rebuild the Lookup setting.
    * 
    * @param mixed $params
    * @return FServiceModel
    */
    public function db2php($params){
        $module = $this->getParam($params, 'module', '');
        //For Cms module, save settings as system's settings
        if ($module == 'Core') $module = '';
        //Get module's params in DB
        Yii::import('Core.models.Lookup', true);
        $criteria = new CDbCriteria(array('select'=>'type','distinct'=>true));
        //$criteria->addCondition("module = '{$module}'");
        $criteria->order = 'type';
        $params = Lookup::model()->findAll($criteria);
        
        $consts = '';
        foreach($params as $param){
            $consts .="\t//lookup type ".$param->type."\n";
            $consts .="\tconst TYPE_".strtoupper(toSlug($param->type,'_'))."='".addslashes($param->type)."';\n";
            
            $criteria1 = new CDbCriteria(array('select'=>'name,code'));
            $criteria1->addCondition("type = '{$param->type}'");
            //$criteria->order = 'position';
            $names = Lookup::model()->findAll($criteria1);
            foreach($names as $name){
            if (!is_numeric($name->code)) 
                $name->code = "'".addslashes($name->code)."'";
            $consts .= "\tconst ".strtoupper(toSlug($param->type,'_')).'_'.strtoupper(toSlug($name->name,'_'))."={$name->code};\n";
            }
        }
        $php = 
"<?php
/**
* DONOT modify this file as it's automatically generated based on setting parameters.
**/
class Lookups{
{$consts}
}
?>";
        $filename = $module.'Lookups.php';
        $path = yii::app()->runtimePath."/cache/";
        
        if (!is_dir($path)){
            $this->result->fail(ServiceResult::ERR_SERVICE_SPECIFIC,'Folder utilities under the module/application folder does not exist.');
            return $this->result;
        }
        
        $f = fopen($path.$filename, 'w+');
        if ($f == false){
            $this->result->fail(ServiceResult::ERR_SERVICE_SPECIFIC,'Cannot create file under utilities folder.');
            return $this->result;
        }
        fwrite($f,$php);
        fclose($f);
        
        return $this->result;
    }
    
    public function findAll($params)
    {
        $type = $this->getParam($params, 'type', '');
        $generate = $this->getParam($params, 'generate', false);
        $data = array();
        $criteria = new CDbCriteria();
        $criteria->compare('type', $type);
        $criteria->order = 'type ASC, position ASC, id DESC';
        $result = Lookup::model()->findAll($criteria);
        if (count($result))
        {
            foreach ($result as $item)
            {
                $data[] = array(
                    'option'=>$item->name,
                    'is_default'=>0,
                    'is_db_live'=>"0",
                    'id'=>$generate ? $item->id : "0",
                );
            }
        }
        return $this->result->processed('data',$data);
    }
}